package com.myproject.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Description: //TODO  简单的HTTP服务器， 其实就是接受HTTP请求，并解析请求，
 * @Author: sunfch
 * @Date: 2019/1/3 16:35
 * @Param:
 * @Return:
 */
public class BioHttpServer2 {

    public static void main(String[] args) {


        try {

            /*监听端口号，只要是8888就能接收到*/
            ServerSocket serverSocket = new ServerSocket(9960);
            System.out.println("服务器准备就绪~");
            System.out.println("服务器信息："+serverSocket.getInetAddress()+" P: "+serverSocket.getLocalPort());

            while (true){
                Socket socket = serverSocket.accept();
                ClientHandler clientHandler = new ClientHandler(socket);
                clientHandler.start();
                System.out.println(socket.toString()+": accept");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ClientHandler extends Thread{

        private Socket socket;

        public ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {

            try {
                /*获取客户端输入流，就是请求过来的基本信息：请求头，换行符，请求体*/
                InputStream inputStream = socket.getInputStream();
                StringBuilder sb = new StringBuilder();
                /**
                 * 接受HTTP请求，并解析数据
                 */
                int b;
                char c;
                while ((b=inputStream.read())!=-1){
                    c = (char) b;
                    sb.append(c);
                    if (sb.toString().endsWith("\r\n\r\n")){
                        break;
                    }
                }


                String[] headers = sb.toString().split("\r\n");
                int contentLength = 0;
                String charset = "gbk";
                for (String header:headers){
                    if (header.contains("Content-Length")){
                        contentLength = Integer.valueOf(header.substring(16));
                    }
                    if (header.contains("charset")){
                        int index = header.indexOf("charset=")+"charset=".length();
                        charset = header.substring(index);
                    }
                }

                byte[] bytes = new byte[contentLength];
                inputStream.read(bytes);
                String body = new String(bytes,charset);
                sb.append(body);
                System.out.println(sb.toString());

                /*发送回执*/
                PrintWriter pw = new PrintWriter(socket.getOutputStream());

                pw.println("HTTP/1.1 200 OK");
                pw.println("Content-type:text/html");
                pw.println();
                pw.println("<h1>successful</h1>");
                pw.flush();

                // close
                inputStream.close();
                pw.close();
                socket.close();
                System.out.println(socket+": close");
            } catch (Exception e){
                System.err.println(Thread.currentThread().getName()+"连接异常断开"+e.getMessage());
                e.printStackTrace();
            }


        }
    }
}